"use client"

import { useState, useEffect } from "react"
import { useParams } from "next/navigation"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  ArrowLeft,
  Edit,
  Save,
  Calendar,
  User,
  Target,
  Clock,
  FileText,
  Users,
  Package,
  History,
  Settings,
  CheckCircle,
  AlertCircle,
  Plus,
  GitBranch,
  GitPullRequest,
  CheckSquare,
  FolderOpen,
  MessageSquare,
  Info
} from "lucide-react"
import { SampleManagement } from "./sample-management"
import { TeamManagement } from "./team-management"
import { HistoryViewer } from "./history-viewer"
import { ProjectDetailTabs } from "./project-detail-tabs"

interface Project {
  id: string
  projectTitle: string
  projectCode: string
  name: string
  projectType: string
  category: string
  applicationType: string
  description: string
  customerName: string
  applicantName: string
  projectManagerName: string
  level1: string
  level2: string
  level3: string
  level4: string
  statusDesc: string
  priority: string
  createTime: string
  updateTime: string
  startDate: string
  endDate: string
  deadline: string
  planStartDate: string
  planEndDate: string
  hasSample: boolean
  sampleCount: number
  creator: {
    id: string
    name: string
    email: string
  }
  versions: any[]
  histories: any[]
  completionPercentage: number
  developmentStatus: string
  progressColor: string
  fullStatusDesc: string
  // 电机参数
  power?: string
  voltage?: string
  current?: string
  ratedSpeed?: string
  ratedTorque?: string
  workTemp?: string
  certification?: string
  lowPower?: string
  startupTime?: string
  conformalCoating?: string
  ratedVoltage?: string
  maxPower?: string
  maxSpeed?: string
  polePairs?: string
  hasHall?: string
  controlMode?: string
  controlAlgorithm?: string
  // 保护参数
  stallProtection?: string
  stallHoldTime?: string
  stallRestartTime?: string
  stallRestartCount?: string
  overvoltageProtection?: string
  overvoltageValue?: string
  overvoltageRecoveryValue?: string
  undervoltageProtection?: string
  undervoltageValue?: string
  undervoltageRecoveryValue?: string
  temperatureProtection?: string
  temperatureValue?: string
  overcurrentProtection?: string
  overcurrentValue?: string
  currentLimitProtection?: string
  currentLimitValue?: string
  blockageProtection?: string
  blockageHoldTime?: string
  blockageRestartTime?: string
  blockageRestartCount?: string
  phaseProtection?: string
  // 控制参数
  controlInterface?: string
  pwmStartDuty?: string
  pwmStopDuty?: string
  pwmDutyRange?: string
  pwmFreqRange?: string
  clockStartFreq?: string
  clockStopFreq?: string
  clockFreqRange?: string
  clockSpeedPowerRange?: string
  clockDuty?: string
  vspStartVoltage?: string
  vspStopVoltage?: string
  vspVoltageRange?: string
  controlDescription?: string
}

interface ProjectState {
  id: string
  name: string
  level: number
  description: string
  color: string
  order: number
}

interface Branch {
  id: string
  name: string
  isMain: boolean
  isActive: boolean
  level: number
  createTime: string
  creatorName: string
  createTimeFormatted: string
}

interface StateHistory {
  id: string
  fromStateDesc: string
  toStateDesc: string
  createdByName: string
  createdTimeFormatted: string
  comment?: string
}

interface Task {
  id: string
  title: string
  description: string
  status: string
  priority: string
  assigneeName: string
  dueDate: string
  createTime: string
}

interface Resource {
  id: string
  name: string
  type: string
  version: string
  addTime: string
  addTimeDisplay: string
  size: string
  uploaderName: string
}

interface Feedback {
  id: string
  title: string
  content: string
  type: string
  typeDesc: string
  status: string
  statusDesc: string
  submitterName: string
  addTime: string
  addTimeDesc: string
}

interface ProjectDetailProps {
  projectId: string
  onBack?: () => void
}

export function ProjectDetail({ projectId, onBack }: ProjectDetailProps) {
  const [project, setProject] = useState<Project | null>(null)
  const [loading, setLoading] = useState(true)
  const [editing, setEditing] = useState(false)
  const [availableStates, setAvailableStates] = useState<ProjectState[]>([])
  const [selectedStates, setSelectedStates] = useState({
    level1: "",
    level2: "",
    level3: "",
    level4: ""
  })

  // 模拟数据 - 在实际应用中应该从API获取
  const [branches] = useState<Branch[]>([
    {
      id: "main",
      name: "主分支",
      isMain: true,
      isActive: true,
      level: 0,
      createTime: "2024-01-01",
      creatorName: "系统管理员",
      createTimeFormatted: "2024-01-01 10:00"
    },
    {
      id: "branch1",
      name: "开发分支",
      isMain: false,
      isActive: true,
      level: 1,
      createTime: "2024-02-01",
      creatorName: "张三",
      createTimeFormatted: "2024-02-01 14:30"
    }
  ])

  const [stateHistory] = useState<StateHistory[]>([
    {
      id: "1",
      fromStateDesc: "草稿",
      toStateDesc: "待立项",
      createdByName: "李四",
      createdTimeFormatted: "2024-01-15 09:30",
      comment: "项目立项申请"
    },
    {
      id: "2",
      fromStateDesc: "待立项",
      toStateDesc: "已立项",
      createdByName: "王五",
      createdTimeFormatted: "2024-01-20 14:20",
      comment: "通过立项评审"
    }
  ])

  const [tasks] = useState<Task[]>([
    {
      id: "1",
      title: "电机控制算法开发",
      description: "开发电机控制算法，包括PID控制和FOC控制",
      status: "IN_PROGRESS",
      priority: "HIGH",
      assigneeName: "张三",
      dueDate: "2024-03-01",
      createTime: "2024-01-25"
    },
    {
      id: "2",
      title: "硬件电路设计",
      description: "设计电机驱动硬件电路",
      status: "PENDING",
      priority: "MEDIUM",
      assigneeName: "李四",
      dueDate: "2024-03-15",
      createTime: "2024-01-26"
    }
  ])

  const [resources] = useState<Resource[]>([
    {
      id: "1",
      name: "电机控制规格书",
      type: "规格书",
      version: "1.0",
      addTime: "2024-01-10",
      addTimeDisplay: "2024-01-10",
      size: "2.5MB",
      uploaderName: "王五"
    },
    {
      id: "2",
      name: "电路原理图",
      type: "设计文档",
      version: "1.2",
      addTime: "2024-01-15",
      addTimeDisplay: "2024-01-15",
      size: "1.8MB",
      uploaderName: "张三"
    }
  ])

  const [feedback] = useState<Feedback[]>([
    {
      id: "1",
      title: "控制算法优化建议",
      content: "建议在FOC控制中加入弱磁控制算法，提高高速区效率",
      type: "IMPROVEMENT",
      typeDesc: "改进建议",
      status: "PENDING",
      statusDesc: "待处理",
      submitterName: "赵六",
      addTime: "2024-01-28",
      addTimeDesc: "2天前"
    }
  ])

  const [currentBranch] = useState<Branch>(branches[0])

  useEffect(() => {
    fetchProject()
    fetchAvailableStates()
  }, [projectId])

  const fetchProject = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/projects/${projectId}`)
      if (response.ok) {
        const data = await response.json()
        setProject(data)
        setSelectedStates({
          level1: data.level1 || "",
          level2: data.level2 || "",
          level3: data.level3 || "",
          level4: data.level4 || ""
        })
      }
    } catch (error) {
      console.error('Error fetching project:', error)
    } finally {
      setLoading(false)
    }
  }

  const fetchAvailableStates = async () => {
    try {
      const response = await fetch('/api/projects/states')
      if (response.ok) {
        const data = await response.json()
        setAvailableStates(data)
      }
    } catch (error) {
      console.error('Error fetching states:', error)
    }
  }

  const getStatusColor = (status: string) => {
    const statusColors: Record<string, string> = {
      'DRAFT': 'bg-gray-100 text-gray-800',
      'IN_PROGRESS': 'bg-blue-100 text-blue-800',
      'REVIEW': 'bg-yellow-100 text-yellow-800',
      'APPROVED': 'bg-green-100 text-green-800',
      'REJECTED': 'bg-red-100 text-red-800',
      'COMPLETED': 'bg-purple-100 text-purple-800'
    }
    return statusColors[status] || 'bg-gray-100 text-gray-800'
  }

  const getPriorityColor = (priority: string) => {
    const priorityColors: Record<string, string> = {
      'HIGH': 'bg-red-100 text-red-800',
      'MEDIUM': 'bg-yellow-100 text-yellow-800',
      'LOW': 'bg-green-100 text-green-800'
    }
    return priorityColors[priority] || 'bg-gray-100 text-gray-800'
  }

  const getStatesByLevel = (level: number) => {
    return availableStates.filter(state => state.level === level)
  }

  const handleStateChange = (level: string, value: string) => {
    setSelectedStates(prev => ({
      ...prev,
      [level]: value
    }))
  }

  const handleSaveStatus = async () => {
    try {
      const response = await fetch(`/api/projects/${projectId}/status`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(selectedStates)
      })

      if (response.ok) {
        await fetchProject()
        setEditing(false)
      }
    } catch (error) {
      console.error('Error updating project status:', error)
    }
  }

  // 事件处理函数
  const handleEditProject = () => {
    console.log('编辑项目')
  }

  const handleEditParams = () => {
    console.log('编辑参数')
  }

  const handleCreateBranch = () => {
    console.log('创建分支')
  }

  const handleManageBranches = () => {
    console.log('管理分支')
  }

  const handleAddTask = () => {
    console.log('添加任务')
  }

  const handleAddResource = () => {
    console.log('添加资源')
  }

  const handleAddFeedback = () => {
    console.log('添加反馈')
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-sm text-gray-500">加载中...</p>
        </div>
      </div>
    )
  }

  if (!project) {
    return (
      <div className="text-center py-12">
        <AlertCircle className="h-12 w-12 text-gray-400 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">项目未找到</h3>
        <p className="text-gray-500">请检查项目ID是否正确</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 顶部工具栏 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="outline" onClick={onBack}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回
          </Button>
          <div>
            <h1 className="text-2xl font-bold">{project.projectTitle}</h1>
            {project.projectCode && (
              <p className="text-gray-500">编码: {project.projectCode}</p>
            )}
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline">
            <Edit className="mr-2 h-4 w-4" />
            编辑项目
          </Button>
        </div>
      </div>

      {/* 项目基本信息 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="h-5 w-5" />
            项目信息
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div>
              <label className="text-sm font-medium text-gray-500">项目名称</label>
              <p className="text-lg">{project.name}</p>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-500">项目类型</label>
              <p>{project.projectType || '未设置'}</p>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-500">优先级</label>
              <Badge className={getPriorityColor(project.priority)}>
                {project.priority}
              </Badge>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-500">负责人</label>
              <div className="flex items-center gap-2">
                <User className="h-4 w-4 text-gray-400" />
                <span>{project.projectManagerName || '未分配'}</span>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-500">创建时间</label>
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-gray-400" />
                <span>{new Date(project.createTime).toLocaleDateString()}</span>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-500">截止日期</label>
              <div className="flex items-center gap-2">
                <Clock className="h-4 w-4 text-gray-400" />
                <span>{project.deadline ? new Date(project.deadline).toLocaleDateString() : '未设置'}</span>
              </div>
            </div>
          </div>
          
          {project.description && (
            <div className="mt-6">
              <label className="text-sm font-medium text-gray-500">项目描述</label>
              <p className="mt-1 text-gray-700">{project.description}</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 4级状态管理 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Target className="h-5 w-5" />
              项目状态管理
            </CardTitle>
            {!editing && (
              <Button variant="outline" onClick={() => setEditing(true)}>
                <Edit className="mr-2 h-4 w-4" />
                编辑状态
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Level 1 */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-500">一级状态</label>
              {editing ? (
                <Select value={selectedStates.level1} onValueChange={(value) => handleStateChange('level1', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {getStatesByLevel(1).map(state => (
                      <SelectItem key={state.id} value={state.name}>
                        {state.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <Badge className={getStatusColor(project.level1)}>
                  {project.level1}
                </Badge>
              )}
            </div>

            {/* Level 2 */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-500">二级状态</label>
              {editing ? (
                <Select value={selectedStates.level2} onValueChange={(value) => handleStateChange('level2', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {getStatesByLevel(2).map(state => (
                      <SelectItem key={state.id} value={state.name}>
                        {state.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <Badge variant="outline">
                  {project.level2 || '未设置'}
                </Badge>
              )}
            </div>

            {/* Level 3 */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-500">三级状态</label>
              {editing ? (
                <Select value={selectedStates.level3} onValueChange={(value) => handleStateChange('level3', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {getStatesByLevel(3).map(state => (
                      <SelectItem key={state.id} value={state.name}>
                        {state.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <Badge variant="outline">
                  {project.level3 || '未设置'}
                </Badge>
              )}
            </div>

            {/* Level 4 */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-500">四级状态</label>
              {editing ? (
                <Select value={selectedStates.level4} onValueChange={(value) => handleStateChange('level4', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {getStatesByLevel(4).map(state => (
                      <SelectItem key={state.id} value={state.name}>
                        {state.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <Badge variant="outline">
                  {project.level4 || '未设置'}
                </Badge>
              )}
            </div>
          </div>

          {project.statusDesc && (
            <div className="mt-4">
              <label className="text-sm font-medium text-gray-500">状态描述</label>
              <p className="mt-1 text-gray-700">{project.statusDesc}</p>
            </div>
          )}

          {editing && (
            <div className="flex justify-end gap-2 mt-6">
              <Button variant="outline" onClick={() => setEditing(false)}>
                取消
              </Button>
              <Button onClick={handleSaveStatus}>
                <Save className="mr-2 h-4 w-4" />
                保存状态
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 项目详情标签页 */}
      <ProjectDetailTabs
        project={project}
        branches={branches}
        stateHistory={stateHistory}
        tasks={tasks}
        resources={resources}
        feedback={feedback}
        currentBranch={currentBranch}
        isAdmin={true} // 应该根据实际用户权限判断
        isOwner={true} // 应该根据实际用户权限判断
        onEditProject={handleEditProject}
        onEditParams={handleEditParams}
        onCreateBranch={handleCreateBranch}
        onManageBranches={handleManageBranches}
        onAddTask={handleAddTask}
        onAddResource={handleAddResource}
        onAddFeedback={handleAddFeedback}
      />
    </div>
  )
}